package com.fly.spring.data.core.config;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Component;

import com.alibaba.druid.pool.DruidDataSource;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 数据源管理
 * 
 * @author 00fly
 * @version [版本号, 2020年6月3日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Deprecated
@Slf4j
@Component
public class MyDataSource
{
    private Map<String, DruidDataSource> dataSourceMap = new ConcurrentHashMap<>();
    
    public void add(String key, DruidDataSource dataSource)
    {
        dataSourceMap.put(key, dataSource);
    }
    
    public DruidDataSource getDataSource(String key)
    {
        if (!dataSourceMap.containsKey(key))
        {
            switch (key)
            {
                case "ds001":
                    createDataSource1();
                    break;
                
                case "ds002":
                    createDataSource2();
                    break;
                
                default:
                    break;
            }
        }
        return dataSourceMap.get(key);
    }
    
    private void createDataSource1()
    {
        log.info("run createDataSource ...");
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl("jdbc:mysql://127.0.0.1:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC");
        ds.setUsername("root");
        ds.setPassword("root123");
        ds.setInitialSize(1);
        ds.setMaxActive(5);
        
        // TODO: 加上会报错IllegalArgumentException: illegal maxActive,待确认原因
        // ds.setMinIdle(10);
        ds.setMaxWait(6000);
        ds.setTimeBetweenEvictionRunsMillis(60000);
        ds.setMinEvictableIdleTimeMillis(300000);
        ds.setTestWhileIdle(true);
        ds.setTestOnBorrow(false);
        ds.setTestOnReturn(false);
        add("ds001", ds);
        
    }
    
    private void createDataSource2()
    {
        log.info("run createDataSource ...");
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl("jdbc:mysql://127.0.0.1:3306/jdbc?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC");
        ds.setUsername("root");
        ds.setPassword("root123");
        ds.setInitialSize(1);
        ds.setMaxActive(5);
        // ds.setMinIdle(10);
        ds.setMaxWait(6000);
        ds.setTimeBetweenEvictionRunsMillis(60000);
        ds.setMinEvictableIdleTimeMillis(300000);
        ds.setTestWhileIdle(true);
        ds.setTestOnBorrow(false);
        ds.setTestOnReturn(false);
        add("ds002", ds);
    }
    
}
